package ee.greaton.kultuuriaken;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.taptwo.android.widget.TitleProvider;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.text.util.Linkify;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class AsyncAdapter extends BaseAdapter implements TitleProvider {

	private LayoutInflater mInflater;

	ViewHolder holder = null;

	EventList list = new EventList();

	boolean online, search;
	boolean geo = true;

	Event event;

	String sTitle, sDescription, sDate, sTime, sImgUrl, sLocation, sCategory,
			sTicketPrice, sETime, sTicketUrl;

	private class ViewHolder {
		View mContent;
		TextView title, description, date, time, location, category,
				ticketPrice, timeS, openMap, viewUrl, ticketS;
		ImageView image;
		View line3, line4;
		LinearLayout menu;
		Bitmap bitmap;
		Event event;
		String imageUrl;

		public void loadImage() {
			new AsyncTask<Void, Void, Void>() {

				@Override
				protected Void doInBackground(Void... voids) {
					InputStream is = null;
					InputStream is2 = null;
					HttpGet httpRequest = new HttpGet(imageUrl);
					HttpClient httpclient = new DefaultHttpClient();
					HttpResponse response = null;
					try {
						response = (HttpResponse) httpclient
						                    .execute(httpRequest);
					} catch (ClientProtocolException e) {} catch (IOException e) {}
					HttpEntity entity = response.getEntity();
					BufferedHttpEntity bufferedHttpEntity;
					try {
						bufferedHttpEntity = new BufferedHttpEntity(entity);
						is = bufferedHttpEntity.getContent();
						is2 = bufferedHttpEntity.getContent();
					} catch (IOException e) {}
					
					bitmap = decodeFile(is, is2);
					try {
						is2.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					return null;
				}

				@Override
				protected void onPostExecute(Void aVoid) {
					image.setImageBitmap(bitmap);
					event.setBitmap(bitmap);
				}
			}.execute();
		}
	}

	public AsyncAdapter(Context context, boolean search) {
		mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		online = Config.online;
		this.search = search;
		prepareEvents();
	}

	public Event getItem(int position) {
		return list.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		return drawView(position, convertView);
	}

	private View drawView(int position, View view) {

		if (view == null) {
			if(Config.theme == 0){
				view = mInflater.inflate(R.layout.tume_single, null);
			}else{
				view = mInflater.inflate(R.layout.hele_single, null);
			}

			setViews(view);

			view.setTag(holder);
		} else {
			holder = (ViewHolder) view.getTag();
		}

		event = getItem(position);
		if (event != null) {
			loadData();
		} else {
			new LoadContentTask().execute(position, view);

			holder.mContent.setVisibility(View.GONE);
		}

		return view;
	}

	public String getTitle(int position) {
		return list.get(position).getTitle();
	}

	public int getCount() {
		return list.size();
	}

	private void prepareEvents() {
		if (!search) {
			list.addAll(KultuuriActivity.eventList1.getAllEvents());
			list.addAll(KultuuriActivity.eventList2.getAllEvents());
			list.addAll(KultuuriActivity.eventList3.getAllEvents());
			list.addAll(KultuuriActivity.eventList4.getAllEvents());
		} else {
			list.addAll(SearchActivity.list.getAllEvents());
		}
	}

	private class LoadContentTask extends AsyncTask<Object, Object, Object> {

		private Integer position;
		private View view;

		@Override
		protected Object doInBackground(Object... arg) {
			position = (Integer) arg[0];
			view = (View) arg[1];

			// long-term task is here
			try {
				Thread.sleep(3000); // do nothing for 3000 miliseconds (3
									// second)
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			return getTitle(position);
		}

		protected void onPostExecute(Object result) {
			// process result

			drawView(position, view);

			view.postInvalidate();
		}

	}

	private void setViews(View view) {
		holder = new ViewHolder();
		holder.title = (TextView) view.findViewById(R.id.singleTitle);
		holder.description = (TextView) view.findViewById(R.id.singleDesc);
		holder.date = (TextView) view.findViewById(R.id.singleDate);
		holder.time = (TextView) view.findViewById(R.id.singleTime);
		holder.location = (TextView) view.findViewById(R.id.singleLocation);
		holder.category = (TextView) view.findViewById(R.id.singleCategory);
		holder.ticketPrice = (TextView) view.findViewById(R.id.singleTicket);
		holder.image = (ImageView) view.findViewById(R.id.singleImage);
		holder.timeS = (TextView) view.findViewById(R.id.sTime);
		holder.openMap = (TextView) view.findViewById(R.id.openMap);
		holder.menu = (LinearLayout) view.findViewById(R.id.singleMenuLinear);
		holder.line3 = view.findViewById(R.id.singleLine3);
		holder.viewUrl = (TextView) view.findViewById(R.id.viewUrl);
		holder.line4 = view.findViewById(R.id.singleLine4);
		holder.ticketS = (TextView) view.findViewById(R.id.sTicket);
	}

	private void loadData() {
		sTitle = event.getTitle();
		sDescription = event.getDescription();
		sDate = event.getDate();
		sTime = event.getTime();
		sImgUrl = event.getImgLink();
		sLocation = event.getLocation();
		sCategory = event.getCategory();
		sTicketPrice = event.getTicketPrice();
		sETime = event.getEtime();
		sTicketUrl = event.getTicketUrl();

		holder.menu.setWeightSum(3);

		holder.image.setVisibility(View.VISIBLE);
		holder.description.setVisibility(View.VISIBLE);
		holder.ticketPrice.setVisibility(View.VISIBLE);
		holder.time.setVisibility(View.VISIBLE);
		holder.timeS.setVisibility(View.VISIBLE);
		holder.openMap.setVisibility(View.VISIBLE);
		holder.line3.setVisibility(View.VISIBLE);
		holder.line4.setVisibility(View.VISIBLE);
		holder.viewUrl.setVisibility(View.VISIBLE);
		holder.ticketS.setVisibility(View.VISIBLE);

		holder.imageUrl = sImgUrl;
		holder.event = event;

		if (event.getGeoLat() == null || event.getGeoLat().equals("")
				|| event.getGeoLong() == null || event.getGeoLong().equals("")) {
			geo = false;
		} else {
			geo = true;
		}

		if (!sTitle.equals("")) {
			holder.title.setText(sTitle);
		}
		if (online && sImgUrl != null && !sImgUrl.equals("")) {
			holder.loadImage();
		} else {
			holder.image.setVisibility(View.GONE);
		}

		if (sLocation != null && !sLocation.equals("")) {
			holder.location.setText(sLocation);
		}

		if (sDate != null && !sDate.equals("")) {
			holder.date.setText(sDate);
		}

		if (sTime != null && !sTime.equals("")) {
			if (sETime == null || sETime.equals("")) {
				holder.time.setText(sTime);
			} else {
				holder.time.setText(sTime + " - " + sETime);
			}
		} else {
			holder.time.setVisibility(View.GONE);
			holder.timeS.setVisibility(View.GONE);
		}

		if (sCategory != null && !sCategory.equals("")) {
			holder.category.setText(sCategory);
		}

		if (sDescription != null && !sDescription.equals("")) {
			holder.description.setText("\n" + replace(sDescription));
			Linkify.addLinks(holder.description, Linkify.WEB_URLS);
		} else {
			holder.description.setVisibility(View.GONE);
		}

		if (sTicketPrice != null && !sTicketPrice.equals("")) {
			holder.ticketPrice.setText(sTicketPrice);
		} else {
			holder.ticketS.setVisibility(View.GONE);
			holder.ticketPrice.setVisibility(View.GONE);
		}
		boolean ticket;
		if (sTicketUrl == null || sTicketUrl.equals("")) {
			ticket = false;
		} else {
			ticket = true;
		}

		if (!geo && ticket) {
			holder.openMap.setVisibility(View.GONE);
			holder.line3.setVisibility(View.GONE);
			holder.menu.setWeightSum(2);
		} else if (!ticket && geo) {
			holder.viewUrl.setVisibility(View.GONE);
			holder.line4.setVisibility(View.GONE);
			holder.menu.setWeightSum(2);
		} else if (!geo && !ticket) {
			holder.openMap.setVisibility(View.GONE);
			holder.line3.setVisibility(View.GONE);
			holder.viewUrl.setVisibility(View.GONE);
			holder.line4.setVisibility(View.GONE);
			holder.menu.setWeightSum(1);
		}
	}

	public String replace(String s) {
		s = s.replaceAll("\\t", "");
		s = s.replaceAll("\\<.*?>", "");
		return s;
	}
	
	private Bitmap decodeFile(InputStream is, InputStream is2){
	    //Decode image size
		BitmapFactory.Options o = new BitmapFactory.Options();
		o.inJustDecodeBounds = true;
		BitmapFactory.decodeStream(is, null, o);

		//The new size we want to scale to
		final int REQUIRED_SIZE=Config.imageSize;

		//Find the correct scale value. It should be the power of 2.
		int scale=1;
		while(o.outWidth/scale>=REQUIRED_SIZE && o.outHeight/scale>=REQUIRED_SIZE){
		    scale*=2;
		}
		try {
			is.close();
		} catch (IOException e) {}
		
		//Decode with inSampleSize
		o.inJustDecodeBounds = false;
		o.inSampleSize=scale;//scale;
		o.inPurgeable= true;
		return BitmapFactory.decodeStream(is2, null, o);
	}
}